package com.bblocks.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;


@Configuration
@EnableAsync
public class ThreadConfig implements AsyncConfigurer {

	@Value("${bblocks.thread.corePoolSize:5}")
	private Integer corePoolSize;
	@Value("${bblocks.thread.maxPoolSize:20}")
	private Integer maxPoolSize;
	@Value("${bblocks.thread.queueCapacity:100}")
	private Integer queueCapacity;

	@Bean(name = "bblocksExecutor")
	@Override
	public Executor getAsyncExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(corePoolSize);// 核心线程数目
		executor.setMaxPoolSize(maxPoolSize);// 最大线程数目
		executor.setQueueCapacity(queueCapacity);// 队列中最大的数目
		executor.setThreadNamePrefix("bb-Executor-"); //指定用于新创建的线程名称的前缀
		executor.initialize();
		return executor;
	}

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return new MyAsyncUncaughtExceptionHandler();
	}
	
}

@Slf4j
class MyAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {
	
    @Override
    public void handleUncaughtException(Throwable ex, Method method, Object... params) {
        log.error("class#method: " + method.getDeclaringClass().getName() + "#" + method.getName());
        log.error("type        : " + ex.getClass().getName());
        log.error("exception   : " + ex.getMessage());
    }
    
}
